package com.example.myhttplibrary.http;


import com.example.myhttplibrary.global.GlobalConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpManager {
    private HttpManager() {

    }

    private static volatile HttpManager httpManager;

    public static HttpManager getInstance() {
        if (httpManager == null) {
            synchronized (HttpManager.class) {
                if (httpManager == null) {
                    httpManager = new HttpManager();
                }
            }
        }
        return httpManager;
    }

    private Retrofit getRetrofit(String baseUrl, long timeout, TimeUnit timeUnit) {
        return new Retrofit
                .Builder()
                .baseUrl(baseUrl)
                .client(getOkhttpClient(timeout, timeUnit))
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private OkHttpClient getOkhttpClient(long timeout, TimeUnit timeUnit) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(timeout, timeUnit);
        builder.writeTimeout(timeout, timeUnit);
        builder.readTimeout(timeout, timeUnit);
        builder.retryOnConnectionFailure(true);

        if (GlobalConfig.getInstance().getInterceptors() != null) {
            for (Interceptor interceptor : GlobalConfig.getInstance().getInterceptors()) {
                builder.addInterceptor(interceptor);
            }
        }
        return builder.build();
    }

    public <T> T createService(Class<T> tClass, String baseUrl, long timeout, TimeUnit timeUnit) {
        return getRetrofit(baseUrl, timeout, timeUnit).create(tClass);
    }

}
